package com.bugmonkey.cameraviewx.watermark;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.FileUtils;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextDirectionHeuristic;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayDeque;

/**
 * 用来放置水印的容器
 */
public class WaterMarkContainerLayout extends FrameLayout {
    public static final String TAG = "WaterMarkContainerLayout";

    private Bitmap bitmap;

    public WaterMarkContainerLayout(@NonNull Context context) {
        this(context, null, 0, 0);
    }

    public WaterMarkContainerLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0, 0);
    }

    public WaterMarkContainerLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public WaterMarkContainerLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        setBackground(null);
    }

    public void setBitmapResource(Bitmap bitmap) {
        this.bitmap = bitmap;
    }

    public void exportWaterMarkBitmap(OnBitmapGeneratedCallback callback) {
        if (bitmap == null) {
            Log.e(TAG, "exportWaterMarkBitmap: 原图bitmap不存在!");
            return ;
        }

        //先把bitmap的尺寸转为控件尺寸
        Bitmap tempBmp = bitmap;
        Log.e(TAG, "exportWaterMarkBitmap: 原图bitmap尺寸："+tempBmp.getWidth()+","+tempBmp.getHeight());
//        Bitmap tempBmp = resizeImage(bitmap,getWidth());
        //遍历子view 创建对应映射
//        traversalView(this,0,0);
        ArrayDeque<View> queue = new ArrayDeque<>();
        queue.addLast(this);


        while (!queue.isEmpty()) {
            Log.e(TAG, "exportWaterMarkBitmap: queue"+queue );
            View temp = (View) queue.getLast();
            queue.pollLast();

            if (temp instanceof ViewGroup && temp.getVisibility() == VISIBLE) {

                int childCount = ((ViewGroup) temp).getChildCount();

                for (int i = childCount-1; i >= 0; i--) {
                    queue.addLast(((ViewGroup) temp).getChildAt(i));
                }

            }

            handleView(temp);

            if (queue.isEmpty()){
                Log.e(TAG, "exportWaterMarkBitmap: 生成成功");
                callback.onBitmapGenerated(bitmap);
            }
        }


//        if (originWidth > getWidth()){
//            return resizeImage(bitmap,originWidth);
//        }

    }

    private float findTopOffset(View view,float offset){
        //遍历直到遇到WaterMarkContainerLayout所有的top叠加

        if (view.getParent() != null && view.getParent() instanceof  WaterMarkContainerLayout){
            return offset + view.getTop();
        }else {
            return findTopOffset(((ViewGroup) view.getParent()),offset+view.getTop()) ;
        }
    }

    private float findLeftOffset(View view,float offset){
        //遍历直到遇到WaterMarkContainerLayout所有的top叠加

        if (view.getParent() != null && view.getParent() instanceof  WaterMarkContainerLayout){
            return offset + view.getLeft();
        }else {
            return findLeftOffset(((ViewGroup) view.getParent()),offset + view.getLeft()) ;
        }
    }


    private synchronized void handleView(View child){
        if (child.getVisibility() == GONE){
            return;
        }

        if (child instanceof  WaterMarkContainerLayout){
            return;
        }

        Log.e(TAG, "handleView: "+child.getClass() );

        float originWidth = bitmap.getWidth();
        float offsetX = findLeftOffset(child,0);
        float offsetY = findTopOffset(child,0);
        bitmap = generateBgWatermark(child, bitmap, originWidth / getWidth(), offsetX, offsetY);

        if (child instanceof TextView) {
            bitmap = generateTextWatermark((TextView) child, bitmap, originWidth / getWidth(), offsetX, offsetY);
        }
        if (child instanceof ImageView) {
            bitmap = generateImageWatermark((ImageView) child, bitmap, originWidth / getWidth(), offsetX, offsetY);
        }

    }

    /**
     * 生成文字水印
     *
     * @param textView
     * @param originBitmap
     * @param scale
     * @param offsetX
     * @param offsetY
     * @return
     */
    private Bitmap generateTextWatermark(TextView textView, Bitmap originBitmap, float scale, float offsetX, float offsetY) {
        if (textView == null || originBitmap == null) {
            return originBitmap;
        }
        Log.e(TAG, "generateTextWatermark" );
        //文字属性
        //文字
        String text = textView.getText().toString();
        //颜色
        int color = textView.getCurrentTextColor();
        Typeface typeface = textView.getTypeface();
        //大小
        float textSize = textView.getTextSize() * scale;
        //位置
        Bitmap.Config bitmapConfig = originBitmap.getConfig();
        // set default bitmap config if none
        if (bitmapConfig == null) {
            bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
        }
        // resource bitmaps are imutable,
        // so we need to convert it to mutable one
        Bitmap bitmap = originBitmap.copy(bitmapConfig, true);

        //开始绘制文字
        Canvas canvas = new Canvas(bitmap);

        TextPaint paint = new TextPaint();
        paint.setColor(color);
        paint.setTextSize(textSize);
        paint.setTypeface(typeface);
        paint.setTextAlign(Paint.Align.LEFT);
        paint.setAntiAlias(true);
        if(textView.getShadowDy()>0){
            paint.setShadowLayer(textView.getShadowRadius(),textView.getShadowDx(),textView.getShadowDy(),textView.getShadowColor());
        }


//        Rect bounds = new Rect();
//        paint.getTextBounds(text,0,text.length(),bounds);
//

        // 绘制多行文字
        StaticLayout layout = StaticLayout.Builder
                .obtain(text, 0, text.length(), paint, (int) (textView.getMeasuredWidth() * scale))
                .setAlignment(Layout.Alignment.ALIGN_NORMAL)
                .build();
        canvas.save();
        canvas.translate((offsetX ) * scale,
                (offsetY ) * scale);
        layout.draw(canvas);
        canvas.restore();
//        float rawX = (offsetX + textView.getRight())*scale - bounds.width()/2f;
//        float rawY = (offsetY + textView.getBottom())*scale - bounds.height()/2f;
//
//        canvas.drawText(text,rawX,rawY,paint);
        Log.e(TAG, "generateTextWatermark:  " + textView.getTop() + "," + textView.getLeft() + "," + textView.getRight() + "," + textView.getBottom());
        Log.e(TAG, "generateTextWatermark: bitmap " + bitmap.getWidth() + "," + bitmap.getHeight());
//        Log.e(TAG, "generateTextWatermark: rawX "+ rawX + ",rawY " +rawY );
        Log.e(TAG, "generateTextWatermark text: " + text);
        return bitmap;

    }

    /**
     * 生成图片水印
     *
     * @param imageView
     * @param originBitmap
     * @param scale
     * @param offsetX
     * @param offsetY
     * @return
     */
    private Bitmap generateImageWatermark(ImageView imageView, Bitmap originBitmap, float scale, float offsetX, float offsetY) {
        if (imageView == null || originBitmap == null) {
            return originBitmap;
        }
        Log.e(TAG, "generateImageWatermark" );
        Bitmap.Config bitmapConfig = originBitmap.getConfig();

        if (bitmapConfig == null) {
            bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
        }

        //待添加的水印图片
        imageView.setDrawingCacheEnabled(true);
        Bitmap overlayBmp = Bitmap.createBitmap(imageView.getDrawingCache());

        imageView.setDrawingCacheEnabled(false);
        if (overlayBmp == null) {
            return originBitmap;
        }

        overlayBmp = resizeImage(overlayBmp, scale);


        Bitmap bitmap = originBitmap.copy(bitmapConfig, true);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawBitmap(overlayBmp, offsetX * scale, offsetY * scale, null);
//        overlayBmp.recycle();
        return bitmap;
    }


    /**
     * 生成背景水印
     * @param view
     * @param originBitmap
     * @param scale
     * @param offsetX
     * @param offsetY
     * @return
     */
    private Bitmap generateBgWatermark(View view, Bitmap originBitmap, float scale, float offsetX, float offsetY) {
        if (view == null || originBitmap == null || view.getBackground() == null || view.getWidth() == 0 || view.getHeight() == 0) {
            return originBitmap;
        }
        Log.e(TAG, "generateBgWatermark" );
        Drawable drawable = view.getBackground();
        // 创建bitmap

        Bitmap drawableBitmap = Bitmap.createBitmap(view.getWidth(),view.getHeight(), originBitmap.getConfig());
        Canvas drawableCanvas = new Canvas(drawableBitmap);
        // 将drawable 内容画到画布中
        drawable.draw(drawableCanvas);

        Canvas canvas = new Canvas(originBitmap);
        canvas.drawBitmap(resizeImage(drawableBitmap,scale), offsetX *scale, offsetY *scale , null);

        return originBitmap;
    }


    public static Bitmap resizeImage(Bitmap originalBitmap, float scale) {
        if(scale == 0){
            return originalBitmap;
        }
        int width = originalBitmap.getWidth();
        int height = originalBitmap.getHeight();

        //操作图片使用的matrix对象 Matrix
        Matrix matrix = new Matrix();
        // 缩放图片动作

        matrix.postScale(scale, scale);

        if(width>0&&height>0){
            //旋转图片 动作
//        matrix.postRotate(45);
            // 创建新的图片Bitmap
            try {
                Bitmap resizedBitmap = Bitmap.createBitmap(originalBitmap, 0, 0, width, height, matrix, true);
                return resizedBitmap;
            }catch (Exception e){
                Log.e(TAG, "resizeImage: "+e.getLocalizedMessage() );
                return originalBitmap;
            }
            // 用完了记得回收
//        resizedBitmap.recycle();

        }else {
            return originalBitmap;
        }

    }


}
